<template>
    <div id="mapContainer" class="mapContainer">
        <div
            style="position: absolute; top: 0; right: 0; z-index: 999; background: white; padding: 10px; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
            <el-checkbox-group v-model="selectedLayers" @change="handleLayerChange">
                <el-checkbox v-for="item in layerList" :key="item.name" :label="item.name" :value="item.name">
                    {{ item.name }}
                </el-checkbox>
            </el-checkbox-group>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Map from '@/map/index';
import jsonData from './中华人民共和国2.json'; //遮罩层数据
// import { weatherPointList } from '@/test/test.js';
import ImageLayer from 'ol/layer/Image';
import dmgis from '@/map/dmgis.js';

let olMap = ref(null); //定义地图实例
let xinjiangVectorLayer = ref(null); //新疆承载体矢量图层
let selectedLayers = ref([]); // 选中的图层列表

onMounted(() => {
    olMap.value = new Map('mapContainer');
    const obj = olMap.value.layer.initLayer(); //初始化底图
    obj.layer.forEach((layer) => {
        const name = layer.get("layerName")
        if (name === '影像图层组') {
            layer.setVisible(true)
        } else {
            layer.setVisible(false)
        }
    })
    let extent = olMap.value.layer.initMaskLayer(jsonData); //添加遮罩层,并将范围全局化
    olMap.value.layer.fitExtentPadding({
        extent: extent
    }); //跳转到遮罩层

    addTile();//添加瓦片
    // addPrj(); //初始化工程
});
let dmProjectLayer;
let layerList = ref([]);
let getPrjImgParam; //获取工程图片参数
const addTile = () => {
    dmProjectLayer = new dmgis.olmap.ServiceLayer('xjczt', '/dmgis', {
        minZoom: 1,
        tileSize: [256, 256]
    });
    //获取工程的所有图层
    dmProjectLayer.InitService().then((res) => {
        layerList.value = res.RESPONSE.SERVER.LAYER;
        console.log("layerList.value:", layerList.value);
    });
};

// 处理图层选择变化
const handleLayerChange = (value) => {
    selectedLayers.value = value;
    console.log('选中的图层:', selectedLayers.value);
    // 这里可以添加显示选中图层的逻辑
    if (selectedLayers.value.length > 0) {
        // 显示第一个选中的图层作为示例
        showimage({ name: selectedLayers.value[0] });
    }
};

const showimage = (item) => {
    layerName.value = item.name
    query()
}
const layerName = ref('大厦');
let tableData = ref([]);
const query = (sql) => {
    //查询参数构建
    let getfeaturePoint = dmProjectLayer.GetFeatureMapService();

    // getfeaturePoint.type = "1"//索引
    // getfeaturePoint.strlist = "1,2,3,4"

    // getfeaturePoint.type = "2"//实体号
    // getfeaturePoint.strlist = "1,2,3,4"

    getfeaturePoint.type = '0'; //条件
    getfeaturePoint.strlayername = layerName.value;
    getfeaturePoint.sql.strSql = sql && sql.length ? sql : 'dmgis_id > 0';

    // var rect = new dmgis.object.Envelope();
    // rect.minx
    // getfeaturePoint.sql.env  = rect;//矩形
    // getfeaturePoint.sql.strPos = "";//多边形
    addDmProject();

    dmProjectLayer.SendFeatureMapService(getfeaturePoint).then((res) => {
        if (res) {
            ElMessage.success('查询成功');
            getPrjImgParam = {
                name: 'QUERY',
                singleLabel: true,
                attributes: {
                    where: sql && sql.length ? sql : 'dmgis_id > 0'
                }
            };
            //两种情况，返回结果为对象则转为数组用来渲染表格
            if (!Object.hasOwn(res.RESPONSE.FEATURES, 'FEATURE') && res.RESPONSE.FEATURES) {
                tableData.value = [];
            } else if (res.RESPONSE.FEATURES.FEATURE.length) {
                tableData.value = res.RESPONSE.FEATURES.FEATURE;
            } else {
                tableData.value = [res.RESPONSE.FEATURES.FEATURE];
            }
            console.log(tableData.value);
        } else {
            ElMessage.error('查询失败');
        }
    })

};
let moveEndListener = null; // 用于保存事件监听器的引用
let serviceLayer = null; //工程图层
let isMoveEndBound = false;
//加载工程图片
const addDmProject = () => {
    if (olMap.value.layer.getLayerByName('工程图片图层')) {
        olMap.value.map.removeLayer(olMap.value.layer.getLayerByName('工程图片图层'));
    }

    dmProjectLayer.serviceLayer = new ImageLayer();
    dmProjectLayer.serviceLayer.setZIndex(2);

    console.log("dmProjectLayer:", dmProjectLayer);
    serviceLayer = dmProjectLayer.serviceLayer;
    serviceLayer.set('layerName', '工程图片图层');

    let imgSvrParam = dmProjectLayer.ImgMapService;

    let extent = olMap.value.map.getView().calculateExtent(olMap.value.map.getSize());
    let size = olMap.value.map.getSize();
    //填参
    imgSvrParam.DispRect.minx = extent[0];
    imgSvrParam.DispRect.miny = extent[1];
    imgSvrParam.DispRect.maxx = extent[2];
    imgSvrParam.DispRect.maxy = extent[3];
    imgSvrParam.imgWid = size[0];
    imgSvrParam.imgHig = size[1];

    let param = {
        name: 'DMGISXML',
        version: '1.1',
        children: {
            name: 'REQUEST',
            children: {
                name: 'GET_IMAGE',
                attributes: {
                    minx: extent[0],
                    miny: extent[1],
                    maxx: extent[2],
                    maxy: extent[3],
                    width: size[0],
                    height: size[1],
                    bclr: '255,255,255',
                    disp: '0'
                },
                children: {
                    name: 'LAYERLIST',
                    children: {
                        name: 'LAYERDEF',
                        attributes: {
                            name: layerName.value,
                            visible: 1
                        },
                        // children: {
                        //     name: 'DISPHIGH',
                        //     attributes: {
                        //         type: 0,
                        //         objtype: 0
                        //     },
                        children: getPrjImgParam
                        // }
                    }
                }
            }
        }
    };

    //通过RefreshMap动态获取工程图片，实现地图的刷新
    dmProjectLayer.RefreshMap(serviceLayer, dmProjectLayer.ImgMapService, param, olMap.value.map.getView().getZoom());
    olMap.value.map.addLayer(serviceLayer);

    // 保存事件监听器的引用
    moveEndListener = function (evt) {
        let frameState = evt.frameState;
        // 填参
        imgSvrParam.DispRect.minx = frameState.extent[0];
        imgSvrParam.DispRect.miny = frameState.extent[1];
        imgSvrParam.DispRect.maxx = frameState.extent[2];
        imgSvrParam.DispRect.maxy = frameState.extent[3];
        imgSvrParam.imgWid = frameState.size[0];
        imgSvrParam.imgHig = frameState.size[1];

        let param = {
            name: 'DMGISXML',
            version: '1.1',
            children: {
                name: 'REQUEST',
                children: {
                    name: 'GET_IMAGE',
                    attributes: {
                        minx: frameState.extent[0],
                        miny: frameState.extent[1],
                        maxx: frameState.extent[2],
                        maxy: frameState.extent[3],
                        width: frameState.size[0],
                        height: frameState.size[1],
                        bclr: '255,255,255',
                        disp: '0'
                    },
                    children: {
                        name: 'LAYERLIST',
                        children: {
                            name: 'LAYERDEF',
                            attributes: {
                                name: layerName.value,
                                visible: 1
                            },
                            // children: {
                            //     name: 'DISPHIGH',
                            //     attributes: {
                            //         type: 0,
                            //         objtype: 0
                            //     },
                            children: getPrjImgParam
                            // }
                        }
                    }
                }
            }
        };
        dmProjectLayer.RefreshMap(serviceLayer, imgSvrParam, param, frameState.viewState.zoom);
    };

    //第一次添加moveend事件
    if (!isMoveEndBound) {
        olMap.value.map.on('moveend', moveEndListener);
        isMoveEndBound = true;
    }
};
</script>

<style scoped>
.mapContainer {
    width: 100%;
    height: 91vh;
    position: relative;
}

button {
    padding: 8px 16px;
    background-color: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

button:hover {
    background-color: #66b1ff;
}
</style>
